home *** CD-ROM | disk | FTP | other *** search
/ Revista do CD-ROM 151 / cd-rom 151.iso / internet / firefox / Firefox Setup 3.0 Beta 1.exe / nonlocalized / components / nsSessionStartup.js < prev    next >
Encoding:
Text File  |  2007-11-09  |  10.8 KB  |  307 lines

  1. /* 
  2. //@line 38 "e:\builds\tinderbox\Fx-Rel\WINNT_5.2_Depend\mozilla\browser\components\sessionstore\src\nsSessionStartup.js"
  3. */
  4.  
  5. /**
  6. //@line 64 "e:\builds\tinderbox\Fx-Rel\WINNT_5.2_Depend\mozilla\browser\components\sessionstore\src\nsSessionStartup.js"
  7. */
  8.  
  9. /* :::::::: Constants and Helpers ::::::::::::::: */
  10.  
  11. const Cc = Components.classes;
  12. const Ci = Components.interfaces;
  13. const Cr = Components.results;
  14. Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
  15.  
  16. const STATE_RUNNING_STR = "running";
  17.  
  18. function debug(aMsg) {
  19.   aMsg = ("SessionStartup: " + aMsg).replace(/\S{80}/g, "$&\n");
  20.   Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService)
  21.                                      .logStringMessage(aMsg);
  22. }
  23.  
  24. /* :::::::: The Service ::::::::::::::: */
  25.  
  26. function SessionStartup() {
  27. }
  28.  
  29. SessionStartup.prototype = {
  30.  
  31.   // the state to restore at startup
  32.   _iniString: null,
  33.  
  34. /* ........ Global Event Handlers .............. */
  35.  
  36.   /**
  37.    * Initialize the component
  38.    */
  39.   init: function sss_init() {
  40.     this._prefBranch = Cc["@mozilla.org/preferences-service;1"].
  41.                        getService(Ci.nsIPrefService).getBranch("browser.");
  42.  
  43.     // if the service is disabled, do not init 
  44.     if (!this._prefBranch.getBoolPref("sessionstore.enabled"))
  45.       return;
  46.  
  47.     // get file references
  48.     var dirService = Cc["@mozilla.org/file/directory_service;1"].
  49.                      getService(Ci.nsIProperties);
  50.     this._sessionFile = dirService.get("ProfD", Ci.nsILocalFile);
  51.     this._sessionFile.append("sessionstore.js");
  52.     
  53.     // only read the session file if config allows possibility of restoring
  54.     var resumeFromCrash = this._prefBranch.getBoolPref("sessionstore.resume_from_crash");
  55.     if ((resumeFromCrash || this._doResumeSession()) && this._sessionFile.exists()) {
  56.       // get string containing session state
  57.       this._iniString = this._readFile(this._sessionFile);
  58.       if (this._iniString) {
  59.         try {
  60.           // parse the session state into JS objects
  61.           var s = new Components.utils.Sandbox("about:blank");
  62.           var initialState = Components.utils.evalInSandbox(this._iniString, s);
  63.  
  64.           // set bool detecting crash
  65.           this._lastSessionCrashed =
  66.             initialState.session && initialState.session.state &&
  67.             initialState.session.state == STATE_RUNNING_STR;
  68.         // invalid .INI file - nothing can be restored
  69.         }
  70.         catch (ex) { debug("The session file is invalid: " + ex); } 
  71.       }
  72.     }
  73.     
  74.     // prompt and check prefs
  75.     this._doRestore = this._lastSessionCrashed ? this._doRecoverSession() : this._doResumeSession();
  76.     if (this._iniString && !this._doRestore) {
  77.       this._iniString = null; // reset the state string
  78.     }
  79.     if (this._prefBranch.getBoolPref("sessionstore.resume_session_once")) {
  80.       this._prefBranch.setBoolPref("sessionstore.resume_session_once", false);
  81.     }
  82.     
  83.     if (this.doRestore()) {
  84.       // wait for the first browser window to open
  85.       var observerService = Cc["@mozilla.org/observer-service;1"].
  86.                             getService(Ci.nsIObserverService);
  87.       observerService.addObserver(this, "domwindowopened", true);
  88.     }
  89.   },
  90.  
  91.   /**
  92.    * Handle notifications
  93.    */
  94.   observe: function sss_observe(aSubject, aTopic, aData) {
  95.     var observerService = Cc["@mozilla.org/observer-service;1"].
  96.                           getService(Ci.nsIObserverService);
  97.  
  98.     switch (aTopic) {
  99.     case "app-startup": 
  100.       observerService.addObserver(this, "final-ui-startup", true);
  101.       break;
  102.     case "final-ui-startup": 
  103.       observerService.removeObserver(this, "final-ui-startup");
  104.       this.init();
  105.       break;
  106.     case "domwindowopened":
  107.       var window = aSubject;
  108.       var self = this;
  109.       window.addEventListener("load", function() {
  110.         self._onWindowOpened(window);
  111.         window.removeEventListener("load", arguments.callee, false);
  112.       }, false);
  113.       break;
  114.     }
  115.   },
  116.  
  117.   /**
  118.    * Removes the default arguments from the first browser window
  119.    * (and removes the "domwindowopened" observer afterwards).
  120.    */
  121.   _onWindowOpened: function sss_onWindowOpened(aWindow) {
  122.     var wType = aWindow.document.documentElement.getAttribute("windowtype");
  123.     if (wType != "navigator:browser")
  124.       return;
  125.     
  126.     /**
  127.      * Note: this relies on the fact that nsBrowserContentHandler will return
  128.      * a different value the first time its getter is called after an update,
  129.      * due to its needHomePageOverride() logic. We don't want to remove the
  130.      * default arguments in the update case, since they include the "What's
  131.      * New" page.
  132.      *
  133.      * Since we're garanteed to be at least the second caller of defaultArgs
  134.      * (nsBrowserContentHandler calls it to determine which arguments to pass
  135.      * at startup), we know that if the window's arguments don't match the
  136.      * current defaultArguments, we're either in the update case, or we're
  137.      * launching a non-default browser window, so we shouldn't remove the
  138.      * window's arguments.
  139.      */
  140.     var defaultArgs = Cc["@mozilla.org/browser/clh;1"].
  141.                       getService(Ci.nsIBrowserHandler).defaultArgs;
  142.     if (aWindow.arguments && aWindow.arguments[0] &&
  143.         aWindow.arguments[0] == defaultArgs)
  144.       aWindow.arguments[0] = null;
  145.     
  146.     var observerService = Cc["@mozilla.org/observer-service;1"].
  147.                           getService(Ci.nsIObserverService);
  148.     observerService.removeObserver(this, "domwindowopened");
  149.   },
  150.  
  151. /* ........ Public API ................*/
  152.  
  153.   /**
  154.    * Get the session state as a string
  155.    */
  156.   get state() {
  157.     return this._iniString;
  158.   },
  159.  
  160.   /**
  161.    * Determine whether there is a pending session restore.
  162.    * @returns bool
  163.    */
  164.   doRestore: function sss_doRestore() {
  165.     return this._doRestore && this._iniString != null;
  166.   },
  167.  
  168. /* ........ Auxiliary Functions .............. */
  169.  
  170.   /**
  171.    * Whether or not to resume session, if not recovering from a crash.
  172.    * @returns bool
  173.    */
  174.   _doResumeSession: function sss_doResumeSession() {
  175.     return this._prefBranch.getIntPref("startup.page") == 3 || 
  176.       this._prefBranch.getBoolPref("sessionstore.resume_session_once");
  177.   },
  178.  
  179.   /**
  180.    * prompt user whether or not to restore the previous session,
  181.    * if the browser crashed
  182.    * @returns bool
  183.    */
  184.   _doRecoverSession: function sss_doRecoverSession() {
  185.     // do not prompt or resume, post-crash
  186.     if (!this._prefBranch.getBoolPref("sessionstore.resume_from_crash"))
  187.       return false;
  188.  
  189.     // if the prompt fails, recover anyway
  190.     var recover = true;
  191.  
  192.     // allow extensions to hook in a more elaborate restore prompt
  193.     // XXXzeniko drop this when we're using our own dialog instead of a standard prompt
  194.     var dialogURI = null;
  195.     try {
  196.       dialogURI = this._prefBranch.getCharPref("sessionstore.restore_prompt_uri");
  197.     }
  198.     catch (ex) { }
  199.     
  200.     try {
  201.       if (dialogURI) { // extension provided dialog 
  202.         var params = Cc["@mozilla.org/embedcomp/dialogparam;1"].
  203.                      createInstance(Ci.nsIDialogParamBlock);
  204.         // default to recovering
  205.         params.SetInt(0, 0);
  206.         Cc["@mozilla.org/embedcomp/window-watcher;1"].
  207.         getService(Ci.nsIWindowWatcher).
  208.         openWindow(null, dialogURI, "_blank", 
  209.                    "chrome,modal,centerscreen,titlebar", params);
  210.         recover = params.GetInt(0) == 0;
  211.       }
  212.       else { // basic prompt with no options
  213.         // get app name from branding properties
  214.         var brandStringBundle = this._getStringBundle("chrome://branding/locale/brand.properties");
  215.         var brandShortName = brandStringBundle.GetStringFromName("brandShortName");
  216.  
  217.         // create prompt strings
  218.         var ssStringBundle = this._getStringBundle("chrome://browser/locale/sessionstore.properties");
  219.         var restoreTitle = ssStringBundle.formatStringFromName("restoredTitle", [brandShortName], 1);
  220.         var restoreText = ssStringBundle.formatStringFromName("restoredMsg", [brandShortName], 1);
  221.         var okTitle = ssStringBundle.GetStringFromName("okTitle");
  222.         var cancelTitle = ssStringBundle.GetStringFromName("cancelTitle");
  223.  
  224.         var promptService = Cc["@mozilla.org/embedcomp/prompt-service;1"].
  225.                             getService(Ci.nsIPromptService);
  226.  
  227.         // set the buttons that will appear on the dialog
  228.         var flags = promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_0 +
  229.                     promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_1 +
  230.                     promptService.BUTTON_POS_0_DEFAULT;
  231.         
  232.         var buttonChoice = promptService.confirmEx(null, restoreTitle, restoreText, 
  233.                                           flags, okTitle, cancelTitle, null, 
  234.                                           null, {});
  235.         recover = (buttonChoice == 0);
  236.       }
  237.     }
  238.     catch (ex) { dump(ex + "\n"); } // if the prompt fails, recover anyway
  239.     return recover;
  240.   },
  241.  
  242.   /**
  243.    * Convenience method to get localized string bundles
  244.    * @param aURI
  245.    * @returns nsIStringBundle
  246.    */
  247.   _getStringBundle: function sss_getStringBundle(aURI) {
  248.     var bundleService = Cc["@mozilla.org/intl/stringbundle;1"].
  249.                         getService(Ci.nsIStringBundleService);
  250.     var appLocale = Cc["@mozilla.org/intl/nslocaleservice;1"].
  251.                     getService(Ci.nsILocaleService).getApplicationLocale();
  252.     return bundleService.createBundle(aURI, appLocale);
  253.   },
  254.  
  255. /* ........ Storage API .............. */
  256.  
  257.   /**
  258.    * reads a file into a string
  259.    * @param aFile
  260.    *        nsIFile
  261.    * @returns string
  262.    */
  263.   _readFile: function sss_readFile(aFile) {
  264.     try {
  265.       var stream = Cc["@mozilla.org/network/file-input-stream;1"].
  266.                    createInstance(Ci.nsIFileInputStream);
  267.       stream.init(aFile, 0x01, 0, 0);
  268.       var cvstream = Cc["@mozilla.org/intl/converter-input-stream;1"].
  269.                      createInstance(Ci.nsIConverterInputStream);
  270.       cvstream.init(stream, "UTF-8", 1024, Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
  271.       
  272.       var content = "";
  273.       var data = {};
  274.       while (cvstream.readString(4096, data)) {
  275.         content += data.value;
  276.       }
  277.       cvstream.close();
  278.       
  279.       return content.replace(/\r\n?/g, "\n");
  280.     }
  281.     catch (ex) { } // inexisting file?
  282.     
  283.     return null;
  284.   },
  285.  
  286.   /* ........ QueryInterface .............. */
  287.   QueryInterface : XPCOMUtils.generateQI([Ci.nsIObserver,
  288.                                           Ci.nsISupportsWeakReference,
  289.                                           Ci.nsISessionStartup]),
  290.   classDescription: "Browser Session Startup Service",
  291.   classID:          Components.ID("{ec7a6c20-e081-11da-8ad9-0800200c9a66}"),
  292.   contractID:       "@mozilla.org/browser/sessionstartup;1",
  293.  
  294.   // get this contractID registered for certain categories via XPCOMUtils
  295.   _xpcom_categories: [
  296.     // make ourselves a startup observer
  297.     { category: "app-startup", service: true }
  298.   ]
  299.  
  300. };
  301.  
  302. //module initialization
  303. function NSGetModule(aCompMgr, aFileSpec) {
  304.   return XPCOMUtils.generateModule([SessionStartup]);
  305. }
  306.  
  307.